package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private RedisCacheService redisCacheService;

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;


    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    /**
     * 数据库同步到redis
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData() {
        clearCache();
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务
        List<Taskinfo> allTasks = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if (allTasks != null && allTasks.size() > 0) {
            for (Taskinfo taskinfo : allTasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    private void clearCache() {
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futureKeys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topicKeys = redisCacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        redisCacheService.delete(futureKeys);
        redisCacheService.delete(topicKeys);
    }


    /**
     * 每一分钟定时刷新未来数据
     */
    //@Scheduled(cron = "0 */1 * * * ?")
    @Scheduled(cron = "*/5 * * * * ?")
    public void refresh() {
       

        //加锁
       // String token = redisCacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
       // if (StringUtils.isNotBlank(token)) {
       //     log.info("未来数据定时刷新---定时任务");
        threadPoolTaskExecutor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");

                try {
                    //休眠2秒钟
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //1.获取所有未来的数据
                for (String futureKeys : redisCacheService.scan(ScheduleConstants.FUTURE + "*")) {
                    //2.获取当前时间的未来数据
                    Set<String> futureKey = redisCacheService.zRangeByScore(futureKeys, 0, System.currentTimeMillis());
                    //3.获取list的key
                    if (!futureKey.isEmpty()) {
                        String topicKey = ScheduleConstants.TOPIC + futureKeys.split(ScheduleConstants.FUTURE)[1];
                        //4.pipuline发给消费者
                        redisCacheService.refreshWithPipeline(futureKeys, topicKey, futureKey);
                        System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                    }
                }
            }
        });

    }


    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {

        Future<Task> future = threadPoolTaskExecutor.submit(new Callable<Task>() {
            @Override
            public Task call() throws Exception {
                //1.获取key值和左边插入的值
                Task task = new Task();
                String key = type + "_" + priority;
                String left = redisCacheService.lLeftPop(ScheduleConstants.TOPIC + key);
                if (!StringUtils.isEmpty(left)) {
                    //2.值转换为task类
                    task = JSON.parseObject(left, Task.class);
                    //3.删除任务表
                    taskinfoMapper.deleteById(task.getTaskId());
                    //4.更新日志表
                    TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                    taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
                    taskinfoLogsMapper.updateById(taskinfoLogs);
                }
                return task;
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    /**
     * 添加延迟任务
     *
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {
        Future<Long> future = threadPoolTaskExecutor.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                //1.添加任务到数据库中
                boolean success = addTaskToDb(task);

                if (success) {
                    //2.添加任务到redis
                    addTaskToCache(task);
                }
                System.out.println("活动线程:" + threadPoolTaskExecutor.getActiveCount());
                return task.getTaskId();
            }
        });
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    /**
     * 把任务添加到redis中
     *
     * @param task
     */
    private void addTaskToCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        //2.1 如果执行时间小于当前时间，则存入list中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            redisCacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }
        //2.2如果执行时间大于当前时间，小于预设时间(当前时间+5分钟)，则存入zset中
        //获取预设时间=当前时间+5分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        //获取当前时间的5分钟之后的毫秒值
        long fiveTime = calendar.getTimeInMillis();
        if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() <= fiveTime) {
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }


    }

    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        boolean flag = false;

        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }
}